Page({
    data: {
        type: 'time',
        receiver: '',
        name: '',
        allowRemote: false,
        needKyc: false,
        startText: '2025-08-21 21:09:19',
        endText: '2025-08-21 21:09:19',
        loopStartText: '2025-08-21',
        loopEndText: '2025-08-28',
        showPicker: '',
        tipText: '*接收者在有效期内可以不限次数使用'
    },
    onBack() { wx.navigateBack(); },
    onChangeType(e) {
        const t = e.currentTarget.dataset.type;
        this.setData({ type: t, tipText: this.computeTip(t) });
    },
    computeTip(t) {
        if (t === 'once') return '*单次钥匙有效期为1小时，只能使用一次';
        if (t === 'forever') return '*接收者可以使用此App开关锁';
        if (t === 'loop') return '*接收者可以在有效期内的固定时间段里，不限次数使用';
        return '*接收者在有效期内可以不限次数使用';
    },
    onInputReceiver(e) { this.setData({ receiver: e.detail.value }); },
    onInputName(e) { this.setData({ name: e.detail.value }); },
    pickStart() { this.setData({ showPicker: 'start' }); },
    pickEnd() { this.setData({ showPicker: 'end' }); },
    pickLoopStart() { this.setData({ showPicker: 'loopStart' }); },
    pickLoopEnd() { this.setData({ showPicker: 'loopEnd' }); },
    onStartConfirm(e) { this.setData({ startText: this.formatDatetime(e.detail), showPicker: '' }); },
    onEndConfirm(e) { this.setData({ endText: this.formatDatetime(e.detail), showPicker: '' }); },
    onLoopStartConfirm(e) { this.setData({ loopStartText: this.formatDate(e.detail), showPicker: '' }); },
    onLoopEndConfirm(e) { this.setData({ loopEndText: this.formatDate(e.detail), showPicker: '' }); },
    onPickerCancel() { this.setData({ showPicker: '' }); },
    toggleRemote(e) { this.setData({ allowRemote: e.detail }); },
    toggleKyc(e) { this.setData({ needKyc: e.detail }); },
    formatDatetime(ts) {
        try { const d = new Date(ts); return this.formatDate(ts) + ` ${this.pad(d.getHours())}:${this.pad(d.getMinutes())}:${this.pad(d.getSeconds())}`; } catch (err) { return String(ts); }
    },
    formatDate(ts) { const d = new Date(ts); return `${d.getFullYear()}-${this.pad(d.getMonth()+1)}-${this.pad(d.getDate())}`; },
    pad(n) { return n < 10 ? `0${n}` : n; },
    onSubmit() { wx.showToast({ title: '已发送（占位）', icon: 'none' }); },
    onBatch() { wx.showToast({ title: '群发钥匙（占位）', icon: 'none' }); }
})